package com.erlang4j.internal.basicIo;

import java.io.IOException;

import com.ericsson.otp.erlang.OtpConnection;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangPid;
import com.erlang4j.api.exceptions.Erland4jExpectedServerNameOrPidException;
import com.erlang4j.api.exceptions.Erlang4jCannotReceiveException;
import com.erlang4j.api.exceptions.Erlang4jCannotSendException;

/** This is IBasicMailBox implementation that is implemented using OtpSelf. This means that it is talking to a remote erlang vm */
public class OtpSelfBasicMailBox implements IBasicMailBox {

	private final OtpConnection connection;

	public OtpSelfBasicMailBox(OtpConnection connection) {
		super();
		this.connection = connection;
	}

	@Override
	public OtpErlangObject receive() {
		try {
			return connection.receive();
		} catch (Exception e) {
			throw new Erlang4jCannotReceiveException(e);
		}
	}

	@Override
	public OtpErlangObject receive(long timeout) {
		try {
			return connection.receive(timeout);
		} catch (Exception e) {
			throw new Erlang4jCannotReceiveException(e);
		}
	}

	@Override
	public void send(Object serverNameOrPid, OtpErlangObject object) {
		try {
			if (serverNameOrPid instanceof String)
				connection.send((String) serverNameOrPid, object);
			else if (serverNameOrPid instanceof OtpErlangPid)
				connection.send((OtpErlangPid) serverNameOrPid, object);
			else
				throw new Erland4jExpectedServerNameOrPidException(serverNameOrPid);
		} catch (IOException e) {
			throw new Erlang4jCannotSendException(e, serverNameOrPid, object);
		}
	}

	@Override
	public OtpErlangPid self() {
		return connection.self().pid();
	}

}
